/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import DialogBoxParams from './DialogBoxParams.js';
import DefaultValueOperator from '../../../scripts/defaultValueOperator.js';

const JS_TAG = 'JS/Component/Dialog Box : '

export default {
  props: ['config', 'data'],
  data: {
    type: 0,
    defaultIndex: [],
    itemCanClick: false,
    parsedData: {},
  },
  onInit() {
    this.$watch('config', 'configUpdate')
    this.$watch('data', 'dataUpdate')
    this.initConfig()
    this.initData()
  },
  configUpdate(newV, oldV) {
    this.initConfig()
  },
  dataUpdate(newV, oldV) {
    this.initData()
  },
  initConfig() {
    if (this.config == undefined) {
      return
    }
    this.type = this.config.type
    this.itemCanClick = DefaultValueOperator.booleanValue(this.config.itemCanClick, this.itemCanClick)
  },
  initData() {
    if (this.data == undefined) {
      return
    }

    let dup = JSON.parse(JSON.stringify(this.data))
    if (this.type == 0) {
      this.parsedData = DialogBoxParams.getTextPickerData(dup)
      this.defaultIndex = DefaultValueOperator.numberValue(this.parsedData.defaultIndex, 0)
    } else if (this.type == 1) {
      this.parsedData = DialogBoxParams.getListSelectorData(dup)
      this.defaultIndex = DefaultValueOperator.arrayValue(this.parsedData.defaultIndex, this.defaultIndex)
    }
  },
  onChangeIndex(changeEvent) {
    this.defaultIndex = changeEvent.detail.index
    this.onClickItem()
  },
  onClickItem() {
    if (!this.itemCanClick) {
      return
    }
    this.$emit('onItemPressed', {
      params: this.defaultIndex
    })
  },
  onClickLeft() {
    this.$emit('onLeftPressed', {
      params: this.defaultIndex
    })
    this.$element('dialog-box').close();
  },
  onClickRight() {
    this.$emit('onRightPressed', {
      params: this.defaultIndex
    })
  },
}